package cn.tedu.service.impl;

import cn.tedu.constant.WxUrlConstant;
import cn.tedu.service.IWxService;
import cn.tedu.util.HttpClientUtil;
import cn.tedu.util.SHA1;
import cn.tedu.vo.AccessTokenBean;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.menu.WxMenu;
import me.chanjar.weixin.common.bean.menu.WxMenuButton;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author Kiven
 */
@Service
public class WxServiceImpl implements IWxService {

    @Value("${wx.token}")
    private String token;

    @Value("${wx.appID}")
    private String appId;

    @Value("${wx.appsecret}")
    private String secret;

    @Value("${wx.baseUrl}")
    private String baseUrl;

    private AccessTokenBean accessTokenBean;



    @Override
    public String createMenu() {
        String redirectUrl = WxUrlConstant.OAUTH2_AUTHORIZE.replace("APPID", appId)
                .replace("REDIRECT_URI", baseUrl + "/wx/getCode")
                .replace("SCOPE", "snsapi_userinfo");
        // 准备菜单
        WxMenu wxMenu = new WxMenu();
        // 准备一级按钮集合
        List<WxMenuButton> firstButtons = new ArrayList<>();
        // 准备一级按钮
        WxMenuButton firstButton = new WxMenuButton();
        firstButton.setName("百度/拍照");
        // 准备二级按钮集合
        List<WxMenuButton> subButtons = new ArrayList<>();
        // 准备二级按钮
        WxMenuButton subButtonOne = new WxMenuButton();
        subButtonOne.setType(WxConsts.MenuButtonType.VIEW);
        subButtonOne.setName("百度去吧你");
        subButtonOne.setUrl(redirectUrl);
        WxMenuButton subButtonTwo = new WxMenuButton();
        subButtonTwo.setName("拍照/相册");
        subButtonTwo.setKey("rselfmenu_1_1");
        subButtonTwo.setType(WxConsts.MenuButtonType.PIC_PHOTO_OR_ALBUM);

        subButtons.add(subButtonOne);
        subButtons.add(subButtonTwo);
        firstButton.setSubButtons(subButtons);
        firstButtons.add(firstButton);
        wxMenu.setButtons(firstButtons);
        // 发送请求
        return HttpClientUtil.doPostJson(WxUrlConstant.CREATE_MENU.replace("ACCESS_TOKEN",getToken()),wxMenu.toJson());
    }





    @Override
    public String getToken() {
        // DCL 双重检测锁
        if(accessTokenBean == null || accessTokenBean.isExpired()){
            synchronized (this){
                if(accessTokenBean == null || accessTokenBean.isExpired()){
                    System.out.println("进来刷新了");
                    refreshToken();
                }
            }
        }
        return accessTokenBean.getAccessToken();
    }



    public  void refreshToken(){
        String s = HttpClientUtil.doGet(WxUrlConstant.ACCESS_TOKEN.replace("APPID",appId)
                .replace("APPSECRET",secret));
        JSONObject jsonObject = JSON.parseObject(s);

        accessTokenBean = AccessTokenBean.responseOf(
                (String)jsonObject.get("access_token"),
                Long.parseLong(jsonObject.get("expires_in")+""));
    }




    @Override
    public void checkWx(String signature, String timestamp, String nonce, String echostr) {
        // 把时间戳随机数token 放到数组并字典排序
        String [] strs = new String[]{timestamp,nonce,token};
        Arrays.sort(strs);
        // 把三个参数拼接 进行SHA1加密
        StringBuilder builder = new StringBuilder();
        for (String str : strs) {
            builder.append(str);
        }
        String selfSignature = SHA1.encode(builder.toString());
        // 进行比较
        if(!selfSignature.equals(signature)){
            throw new RuntimeException("请勿非法访问");
        }
    }


}
